distance_cal <- function(v1 = c(), v2 = c()){
  if(length(v1) != length(v2)){
    return(NA)
  }else{
    sum_sq <- 0
    for(i in 1:length(v1)){
      sum_sq <- sum_sq + (v1[i] - v2[i])^2
    }
    return(sum_sq^0.5)
  }
}

#### test area 1 ####
# distance_cal(c(1,6), c(2,3))
# distance_cal(c(1,6,1), c(2,3,2))

vecs_mean <- function(x = matrix()){
  mean_vec <- rep(0, dim(x)[2])
  for(i in 1:dim(x)[2]){
    mean_vec[i] <- mean(x[,i])
  }
  return(mean_vec)
}

#### test area 2 ####
# vecs_mean(matrix(rnorm(20),nrow = 4))

my_kmeans <- function(x = matrix(), groups = c()){
  if(dim(x)[1] != length(groups)){
    return("ERROR")
  }
  cate_num <- length(unique(groups))
  cates <- unique(groups)
  
  # cal center
  centers <- matrix(rep(0, cate_num * dim(x)[2]), nrow = cate_num)
    for(i in 1:cate_num){
      centers[i,] <- vecs_mean(x[groups == cates[i],])
    }
  
  # re cates for each points
  new_groups <- rep(0, dim(x)[1])
  for(i in 1:dim(x)[1]){
    dis_vec <- rep(0, cate_num)
    for(j in 1:cate_num){
      dis_vec[j] <- distance_cal(v1 = centers[j,], v2 = x[i,])
    }
    new_groups[i] <- cates[grep(x = dis_vec, pattern = min(dis_vec))][1]
  }
  return(new_groups)
}


#### test area 3 ####

# create data

# x  <- matrix(c(rnorm(100, mean = 1, sd = 0.5), 
#              rnorm(50, mean = 2, sd = 0.5), 
#              rnorm(100, mean = 5, sd = 0.5), 
#              rnorm(50, mean = 1, sd = 0.5)),
#              ncol = 2,
#              byrow  = F
#              )
# groups <- sample(x = c(1,2,3,4,5), size = 150, replace = T)
# 
# library(ggplot2)
# plot_df <- data.frame(x[,1], x[,2], groups)
# names(plot_df) <- c("x_ax", "y_ax", "types")
# ggplot(plot_df, aes(x = x_ax, y = y_ax, color = types)) + geom_point()
# 
# ####--------------loop
# groups <- my_kmeans(x = x, groups = groups)
# # groups <- new_groups
# library(ggplot2)
# plot_df <- data.frame(x[,1], x[,2], groups)
# names(plot_df) <- c("x_ax", "y_ax", "types")
# ggplot(plot_df, aes(x = x_ax, y = y_ax, color = types)) + geom_point()
